package com.topisv.tms.service.work.prepkg;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.apache.commons.lang.StringUtils;
import org.hibernate.ejb.criteria.predicate.ComparisonPredicate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.topisv.tms.entity.stock.CusStock;
import com.topisv.tms.entity.work.prepkg.PrepkgPickItem;
import com.topisv.tms.entity.work.prepkg.PrepkgPickTask;
import com.topisv.tms.entity.work.prepkg.PrepkgPkgItem;
import com.topisv.tms.entity.work.prepkg.PrepkgPkgTask;
import com.topisv.tms.entity.work.prepkg.PrepkgPlan;
import com.topisv.tms.repository.stock.CusStockDao;
import com.topisv.tms.repository.work.prepkg.PrepkgPickItemDao;
import com.topisv.tms.repository.work.prepkg.PrepkgPickTaskDao;
import com.topisv.tms.repository.work.prepkg.PrepkgPkgItemDao;
import com.topisv.tms.repository.work.prepkg.PrepkgPkgTaskDao;
import com.topisv.tms.repository.work.prepkg.PrepkgPlanDao;
import com.topisv.tms.utils.rule.TMSTransportRule;

/**
 * 预包装拣货任务_service
 * @author ch
 */
@Component
@Transactional(readOnly = true)
public class PrepkgPickTaskService {

	@Autowired
	private PrepkgPickTaskDao prepkgPickTaskDao;
	@Autowired
	private PrepkgPlanDao prepkgPlanDao;
	@Autowired
	private PrepkgPickItemDao prepkgPickItemDao;
    @Autowired
    private CusStockDao cusStockDao;
    @Autowired
    private PrepkgPkgTaskDao prepkgPkgTaskDao;
    @Autowired
    private PrepkgPkgItemDao prepkgPkgItemDao;
	
	/**
	 * 查找任务
	 * @param param 查询参数
	 * @return
	 */
	public List<PrepkgPickTask> loadTaskByParam(Map<String, Object> param) {
		Specification<PrepkgPickTask> spec = getWhereClause(param);
		List<PrepkgPickTask> workTaskList = this.prepkgPickTaskDao.findAll(spec);
		return workTaskList;
	}
	
	/**
	 * 查询条件封装
	 * @param param
	 * @return
	 */
	private Specification<PrepkgPickTask> getWhereClause(final Map<String, Object> param) {
		return new Specification<PrepkgPickTask>(){
			@Override
		    public Predicate toPredicate(Root<PrepkgPickTask> r, CriteriaQuery<?> q, CriteriaBuilder cb) {
		      Predicate pre = cb.conjunction();
		      
		      //customerCodes
		      String customerCodes=(String) param.get("customerCodes");
		      if(StringUtils.isNotBlank(customerCodes)) {
		    	  String[] customerCodeSplit = customerCodes.split(":");
				  ComparisonPredicate[] tempCustomerCode = new ComparisonPredicate[customerCodeSplit.length];
				  int i = 0;
				  for (String _customerCode : customerCodeSplit) {
					 tempCustomerCode[i] = (ComparisonPredicate) cb.equal(r.get("customerCode"), _customerCode);
					 i++;
				  }
				  pre.getExpressions().add(cb.or(tempCustomerCode));
		      }
			  
		      //areagroups
		      String areagroups=(String) param.get("areagroups");
		      if(StringUtils.isNotBlank(areagroups)) {
		    	  String[] areagroupSplit = areagroups.split(":");
				  ComparisonPredicate[] areagroupArray = new ComparisonPredicate[areagroupSplit.length];
				  int j = 0;
				  for (String _areagroup : areagroupSplit) {
						areagroupArray[j] = (ComparisonPredicate) cb.equal(r.get("warehouseCode"), _areagroup);
						j++;
				  }
				  pre.getExpressions().add(cb.or(areagroupArray));
			  }
		      
		      Date fromDate= (Date) param.get("fromDate");
		      if (fromDate != null) {
		        pre.getExpressions().add(cb.greaterThanOrEqualTo(r.<Date>get("createTime"), fromDate));
		      }
		      
		      Date toDate= (Date) param.get("toDate");
		      if (toDate != null) {
		        pre.getExpressions().add(cb.lessThanOrEqualTo(r.<Date>get("createTime"), toDate));
		      }
		      
		      String status=(String) param.get("status"); 
		      if(StringUtils.isNotBlank(status)){
		    	  if(status.equals("myTask")){ //我的拣货任务
		    		  pre.getExpressions().add(cb.or(
		    				  cb.equal(r.get("status"),"token"),
		    				  cb.equal(r.get("status"),"doing")
		    				  ));
		    	  }
		    	  else{
		    		  pre.getExpressions().add(cb.equal(r.get("status"),status)); 
		    	  }
			  }
		      
		      String workerUuid=(String) param.get("workerUuid");
		      if(StringUtils.isNotBlank(workerUuid)){
					pre.getExpressions().add(cb.equal(r.get("workerUuid"),workerUuid));
			  }	
		      
		      return pre;
		    }
		  };
       }

	/**
	 * 领取任务
	 * @param taskId 任务ID
	 * @param userId 任务执行人
	 * @throws Exception 
	 */
	@Transactional(readOnly = false,rollbackFor=Exception.class)
	public void takeTask(Long taskId, String jobuuid) throws Exception{
		
		try {
			
			PrepkgPickTask task=this.prepkgPickTaskDao.findOne(taskId);
			if(!"undo".equals(task.getStatus())){
				throw new Exception("任务已经被领取");
			}
			
			//修改拣货任务状态
			task.setWorkerUuid(jobuuid);
			task.setStatus("token"); 
			this.prepkgPickTaskDao.save(task);
			
			
			//修改出库单状态
			PrepkgPlan plan=this.prepkgPlanDao.loadByPlanCode(task.getPlanCode());
			plan.setStatus("tokePickTask"); //tokePickTask:领取拣货任务
			this.prepkgPlanDao.save(plan);
		
		} catch (Exception e) {
			
			throw e;
		}
		
	}

	/**
	 * 查询任务
	 * @param taskId
	 * @return
	 */
	public PrepkgPickTask loadTaskById(Long taskId) {
		PrepkgPickTask task=this.prepkgPickTaskDao.findOne(taskId);
		return task;
	}

	/**
	 * 完成拣货任务
	 * @param taskId
	 * @throws Exception 
	 */
	@Transactional(readOnly = false,rollbackFor=Exception.class)
	public void completeTask(Long taskId) throws Exception {
		try {
			
			Date now=new Date();
			
			//修改拣货任务状态
			PrepkgPickTask task=this.prepkgPickTaskDao.findOne(taskId);
			task.setStatus("finish");
			this.prepkgPickTaskDao.save(task);
			
			//修改计划状态
			PrepkgPlan plan=this.prepkgPlanDao.loadByPlanCode(task.getPlanCode());
			plan.setStatus("cmpPickTask"); //状态 （cmpPickTask. 完成拣货任务 )
			this.prepkgPlanDao.save(plan);
			
			//修改库存数据
			List<PrepkgPickItem> itemList=this.prepkgPickItemDao.loadByTaskCode(task.getTaskCode());
			for (PrepkgPickItem item : itemList) {
				String customerCode=item.getCustomerCode();
				String warehouseCode=item.getWarehouseCode();
				String stockCode=item.getStockCode();
				String boxCode=item.getBoxCode();
				String sku=item.getSku();
				Integer num=item.getNum();
				
				CusStock stock=this.cusStockDao.loadStock(customerCode, warehouseCode, stockCode, boxCode, sku);
				if(stock==null){
					throw new Exception("库存异常");
				}
				if(stock.getOrderNum() - num < 0){//add by LiBin 20160808
                    throw new Exception("订单占用库存异常：stockCode:"+stockCode+" sku:" + sku);
                }
				stock.setOrderNum(stock.getOrderNum()-num);
				this.cusStockDao.save(stock);
			}
			
			//创建包装任务
			PrepkgPkgTask pkgTask=new PrepkgPkgTask();
			pkgTask.setCreateTime(now);
			pkgTask.setCustomerCode(task.getCustomerCode());
			pkgTask.setGoodsNum(task.getGoodsNum());
			pkgTask.setPlanCode(task.getPlanCode());
			pkgTask.setSkuNum(task.getSkuNum());
			pkgTask.setStatus("undo");
			pkgTask.setTaskCode(TMSTransportRule.generatePreTaskCode());
			pkgTask.setWarehouseCode(task.getWarehouseCode());
			this.prepkgPkgTaskDao.save(pkgTask);
			
			//创建包装明细
			List<PrepkgPickItem> pickItemList=this.prepkgPickItemDao.loadByTaskCode(task.getTaskCode());
			Map<String, Integer> map=new HashMap<String, Integer>();
			for (PrepkgPickItem pickItem : pickItemList) {
				String sku=pickItem.getSku();
				Integer num=pickItem.getNum();
				
				if(map.containsKey(sku)){
					map.put(sku, map.get(sku)+num);
				}else{
					map.put(sku, num);
				}
			}
			for(String sku: map.keySet()){
				PrepkgPkgItem pkgItem=new PrepkgPkgItem();
				pkgItem.setCustomerCode(task.getCustomerCode());
				pkgItem.setNum(map.get(sku));
				pkgItem.setPlanCode(task.getPlanCode());
				pkgItem.setSku(sku);
				pkgItem.setStatus("unpkged");
				pkgItem.setTaskCode(pkgTask.getTaskCode());
				pkgItem.setWarehouseCode(task.getWarehouseCode());
				this.prepkgPkgItemDao.save(pkgItem);
			}
			
			
		} catch (Exception e) {
			
			throw e;
		}
	}

}